package com.abe.jetpack.viewmodel

import android.arch.lifecycle.*
import com.abe.jetpack.model.entity.http.AuthorEntity
import com.abe.jetpack.model.repository.AuthorRepository
import com.abe.libcore.utils.CommonUtils
import com.uber.autodispose.AutoDispose
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject

class WanAndroidModel @Inject constructor(private val authorRep: AuthorRepository) : ViewModel() {
    private val loading: CusLiveData<Boolean> = CusLiveData(false)
    private var authorEntities: MutableLiveData<List<AuthorEntity>>? = null
    private var authorNames: LiveData<List<String>>? = null

    fun getAllName(): LiveData<List<String>> {
        if (authorNames == null) {
            authorNames = Transformations.map(authorEntities!!) { input ->
                val names = arrayListOf<String>()
                for (AuthorEntity: AuthorEntity in input!!) {
                    names.add(AuthorEntity.name!!)
                }
                names
            }
        }
        return authorNames!!
    }

    fun getAuthors(lifecycle: Lifecycle): LiveData<List<AuthorEntity>> {
        if (authorEntities == null) {
            authorEntities = MutableLiveData()
            loadAuthors()
                    .`as`(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(lifecycle)))
                    .subscribe({}, { CommonUtils.log("httpTest:" + it.message) })
        }
        return authorEntities!!
    }

    fun loadAuthors(): Single<List<AuthorEntity>> {
        return authorRep.remoteAuthors()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSuccess {
                    authorEntities!!.postValue(it)
                }
                .doOnSubscribe {
                    loading.postValue(true)
                }
                .doAfterTerminate {
                    loading.postValue(false)
                }
    }
}